<template>
  <div class="sendtalk zanwei-top">
    <head-nav></head-nav>
    <!-- <h2>选择图片</h2>
    <div>
      <input type="file" accept="image/*" capture="camera" @change="imageFileChange">
    </div>
    <br>
    <br>
    <br>
    <h3>压缩之前的图片</h3>
    <img :src="compressFrondImage" alt="">
    <h3>压缩之后的图片</h3>
    <img :src="compressEndImage" alt=""> ======================= -->
    <!--<div class="some">
			<mt-field class="inbox user" label="标题" placeholder="请输入标题" v-model="title"></mt-field>
			<mt-field class="inbox" label="内容" placeholder="请输入内容" type="textarea" rows="4" v-model="description"></mt-field>
		</div>-->
    <div class="st_box">
      <div class="title">
        <input type="text" v-model="title" placeholder="请输入标题" />
      </div>
        <div class="kanfa">
<!--          :style="{borderColor:primaryColor}"-->
          <div class="whead" >发表内容</div>
          <mt-field class="inbox" placeholder="此时此刻您想说点什么..." type="textarea" rows="4" v-model="description"></mt-field>
        </div>
        <div class="upph">
          <div class="chooseImg">
            <!--<div class='head'>
						<span>请选择图片</span>
						<div>{{tempFilePaths.length}}</div>
					</div>-->
<!--            :style="{borderColor:primaryColor}"-->
            <div class="whead" >选择图片</div>
            <div class="page-body-info">
              <div class='hasPh' v-for="(item,index) in tempFilePaths" :key="index">
                <div class="phbox">
                  <img :src="item" class="image" />
              </div>
                  <div class='clear' @click='clearImg(index)'>×</div>
                </div>
                <!--<img v-for="(item,index) in arr" :src="item" :key="index" style="width: 1rem;height: 1rem;" />-->
                <!--<div class="chooseBtn" v-if="hideAdd" @click="carm">
							<div class="line-horizontal"></div>
							<div class="line-vertical"></div>
						</div>-->
                <div class="chooseBtn" v-if="hideAdd">
                  <div class="line-horizontal"></div>
                  <div class="line-vertical"></div>
                  <div class="add">添加</div>
                  <input type="file" accept="image/*" @change="imageFileChange" name="file" ref="inputer" /> <!-- handleFileChange   imageFileChange -->
                </div>
              </div>
            </div>
          </div>
          <div class="tis">
            <i class="iconfont icon-jinggao"></i>
            <span>发布成功后需审核, 请您耐心等待!</span>
          </div>
<!--      :style="backgroundColor"-->
          <div class="sendBtn" @click="sendArt" >
            <span>发</span>
            <span>布</span>
          </div>
        </div>
      </div>
</template>

<script>
import EXIF from "exif-js";
import api from "@/api/api";
import { Field, Toast, MessageBox } from "mint-ui";
export default {
  data() {
    return {
      title: "",
      description: "",
      tempFilePaths: [],
      hideAdd: true,
      userid: "",
      selImg: "",
      multiple: true,
      file: "",
      arr: [],
      testph: [],
      compressFrondImage: "", // 压缩之前的图片
      compressEndImage: "" // 压缩之后的图片
    };
  },
  methods: {
    handleFileChange(e) {
      let that = this;
      let afile = e.target.files[0];
      if (this.testph.length >= 6) {
        Toast({
          message: "您上传的图片已经够多了",
          duraiton: 1500
        });
        return;
      }
      let reader = new FileReader();
      new Promise((resolve, reject) => {
        reader.readAsDataURL(afile);
        reader.onload = function(e) {
          resolve(e);
        };
      }).then(e => {
        that.tempFilePaths.push(e.target.result);
        that.testph.push(afile);
      });
    },
    clearImg(index) {
      this.tempFilePaths.splice(index, 1);
      var arr = this.tempFilePaths;
      this.tempFilePaths = arr;
      // 对应删除
      this.testph.splice(index, 1);
      var arr2 = this.testph;
      this.testph = arr2;
    },
    sendArt() {
      let that = this;
      let userid = this.userid;
      let title = this.title;
      let description = this.description;
      let fjarr = that.testph;
      if (title === "") {
        Toast({
          message: "请填写标题",
          duration: 1500
        });
        return false;
      }
      api.uploadQtArticles(that, userid, title, description, function(res) {
        console.log(res);
        let data = JSON.parse(res.data.data);
        if (data.code === 1) {
          let sid = data.id;
          // 上传图片
          console.log(sid);
          if (fjarr.length > 0) {
            // 有图片
            let num = 0;
            // alert(fjarr[num])
            uploadph();
            function uploadph() {
              api.upload(
                that,
                fjarr[num],
                userid,
                sid,
                "ht",
                "2c91a36a605505f5016059d26400024d",
                function(res) {
                  let data = res.data;
                  if (data.code === 0) {
                    num++;
                    if (num === fjarr.length) {
                      Toast({
                        message: "恭喜您发表成功,请等待审核",
                        duraion: 1500
                      });
                      setTimeout(function() {
                        that.$router.go(-1);
                      }, 1600);
                      return;
                    }
                    uploadph();
                  } else {
                    Toast({
                      message: "图片上传失败",
                      duraion: 1000
                    });
                  }
                }
              );
            }
          } else {
            Toast({
              message: "恭喜您发表成功,请等待审核",
              duraion: 1500
            });
            setTimeout(function() {
              that.$router.go(-1);
            }, 1600);
          }
        } else {
          Toast({
            message: res.msg,
            duration: 1500
          });
        }
      });
    },

    // 图片开始
    /**
     * 图片文件发生变化
     */
    imageFileChange(e) {
      this.file = e.target.files[0];
      if (this.file) {
        if (this.testph.length >= 6) {
          Toast({
            message: "您上传的图片已经够多了",
            duraiton: 1500
          });
          return;
        } else {
          let reader = new FileReader();
          reader.readAsDataURL(this.file);
          reader.onload = e => {
            console.log(e.target);
            this.compressFrondImage = e.target.result;
            this.compressImages(this.compressFrondImage);
          };
        }
      }
    },
    compressImages(res) {
      let defaultImage = {
        width: 1440,
        height: 1080,
        quality: 0.8, // 压缩图片的质量
        orientation: "" // 获取照片方向角属性，用户旋转控制
      };
      var img = new Image();
      img.src = res;
      let initSize = img.src.length;
      img.onload = () => {
        // 方便手机测试
        // alert("压缩之前宽度： " + img.width);
        // alert("压缩之前高度： " + img.height);
        // 方便浏览器测试
//      alert("压缩之前宽度： " + img.width);
        console.log("压缩之前高度： " + img.height);
        var canvas = document.createElement("canvas");
        var ctx = canvas.getContext("2d");
        if (img.width > defaultImage.width) {
          img.height = img.height * (defaultImage.width / img.width);
          img.width = defaultImage.width;
        }
        if (img.height > defaultImage.height) {
          img.width *= defaultImage.height / img.height;
          img.height = defaultImage.height;
        }
        canvas.width = img.width;
        canvas.height = img.height;
        ctx.clearRect(0, 0, canvas.width, canvas.height);
        EXIF.getData(this.file, () => {
          // IMG_FILE为图像数据
          // 是否是iPhone手机，iPhone 拍照之后的压缩是逆时针旋转90，针对iphone做一下处理
          if (navigator.userAgent.match(/iphone/i)) {
            defaultImage.orientation = EXIF.getTag(this.file, "Orientation");
            // translate是平移变换，scale(-1,1)是向左翻转，rotate是顺时针旋转。
            // defaultImage.orientation = 6   // 测试iPhone手机
            // alert("Orientation:" + defaultImage.orientation); // 拍照方向
            switch (Number(defaultImage.orientation)) {
              case 2:
                ctx.translate(img.width, 0);
                ctx.scale(-1, 1);
                ctx.drawImage(img, 0, 0, img.width, img.height);
                break;
              case 3:
                ctx.rotate((180 * Math.PI) / 180);
                ctx.drawImage(
                  img,
                  -img.width,
                  -img.height,
                  img.width,
                  img.height
                );
                break;
              case 4:
                ctx.translate(img.width, 0);
                ctx.scale(-1, 1);
                ctx.rotate((180 * Math.PI) / 180);
                ctx.drawImage(
                  img,
                  -img.width,
                  -img.height,
                  img.width,
                  img.height
                );
                break;
              case 5:
                ctx.translate(img.width, 0);
                ctx.scale(-1, 1);
                ctx.rotate((90 * Math.PI) / 180);
                ctx.drawImage(img, 0, -img.width, img.height, img.width);
                break;
              case 6:
                canvas.width = img.height;
                canvas.height = img.width;
                ctx.rotate((90 * Math.PI) / 180);
                ctx.drawImage(img, 0, 0, img.width, -img.height);
                break;
              case 7:
                ctx.translate(img.width, 0);
                ctx.scale(-1, 1);
                ctx.rotate((270 * Math.PI) / 180);
                ctx.drawImage(img, -img.height, 0, img.height, img.width);
                break;
              case 8:
                ctx.rotate((270 * Math.PI) / 180);
                ctx.drawImage(img, -img.height, 0, img.height, img.width);
                break;
              default:
                ctx.drawImage(img, 0, 0, img.width, img.height);
            }
          } else {
            ctx.drawImage(img, 0, 0, img.width, img.height);
          }
          var imgUrl = canvas.toDataURL("image/jpeg", defaultImage.quality);
          // 手机端测试
          // alert(
          //   "压缩率：" + ~~(100 * (initSize - imgUrl.length) / initSize) + "%"
          // );
          // alert("压缩之后宽度： " + img.width);
          // alert("压缩之后高度： " + img.height);
          // 浏览器测试
          // console.log("压缩前：" + initSize);
          // console.log("压缩后：" + imgUrl.length);
          console.log(
            "压缩率：" + ~~((100 * (initSize - imgUrl.length)) / initSize) + "%"
          );
          // console.log("压缩之后宽度： " + img.width);
          // console.log("压缩之后高度： " + img.height);
          console.log("压缩之后base64地址");
//        alert(imgUrl);
          // 压缩之后的base64 图片地址
          this.compressEndImage = imgUrl;
          // that.testph.push(afile);
          this.tempFilePaths.push(imgUrl);
          // 开始base64转formdata格式上传  这个转化formdata有问题
          // function dataURLtoFile(dataurl, filename) {
          //   //将base64转换为文件
          //   var arr = dataurl.split(","),
          //     mime = arr[0].match(/:(.*?);/)[1],
          //     bstr = atob(arr[1]),
          //     n = bstr.length,
          //     u8arr = new Uint8Array(n);
          //   while (n--) {
          //     u8arr[n] = bstr.charCodeAt(n);
          //   }
          //   return new File([u8arr], filename, {
          //     type: mime
          //   });
          // }
          //var blob = dataURLtoFile(imgUrl, "img.jpg");
          function dataURItoBlob(base64Data) {
            var byteString;
            if (base64Data.split(",")[0].indexOf("base64") >= 0)
              byteString = atob(base64Data.split(",")[1]);
            else byteString = unescape(base64Data.split(",")[1]);
            var mimeString = base64Data
              .split(",")[0]
              .split(":")[1]
              .split(";")[0];
            var ia = new Uint8Array(byteString.length);
            for (var i = 0; i < byteString.length; i++) {
              ia[i] = byteString.charCodeAt(i);
            }
            return new Blob([ia], { type: mimeString });
          }
          var blob = dataURItoBlob(imgUrl); // base64 转formdata
          
          //结束base64转换

          this.testph.push(blob);

          // TODO 上传图片文件
          this.uploadImage();
        });
      };
    },
    /**
     * 上传图片
     */
    uploadImage: function() {},
    /**
     * 瓦片压缩 正在测试
     */
    imagesCompress: function(img) {
      // 用于压缩图片的canvas
      var canvas = document.createElement("canvas");
      var ctx = canvas.getContext("2d");
      // 瓦片canvas
      var tCanvas = document.createElement("canvas");
      var tctx = tCanvas.getContext("2d");

      var initSize = img.src.length;
      var width = img.width;
      var height = img.height;

      // 如果图片大于四百万像素，计算压缩比并将大小压至400万以下
      var ratio;
      if ((ratio = (width * height) / 4000000) > 1) {
        ratio = Math.sqrt(ratio);
        width /= ratio;
        height /= ratio;
      } else {
        ratio = 1;
      }

      canvas.width = width;
      canvas.height = height;

      // 铺底色
      ctx.fillStyle = "#fff";
      ctx.fillRect(0, 0, canvas.width, canvas.height);

      // 如果图片像素大于100万则使用瓦片绘制
      var count;
      if ((count = (width * height) / 1000000) > 1) {
        count = ~~(Math.sqrt(count) + 1); // 计算要分成多少块瓦片

        // 计算每块瓦片的宽和高
        var nw = ~~(width / count);
        var nh = ~~(height / count);

        tCanvas.width = nw;
        tCanvas.height = nh;

        for (var i = 0; i < count; i++) {
          for (var j = 0; j < count; j++) {
            tctx.drawImage(
              img,
              i * nw * ratio,
              j * nh * ratio,
              nw * ratio,
              nh * ratio,
              0,
              0,
              nw,
              nh
            );

            ctx.drawImage(tCanvas, i * nw, j * nh, nw, nh);
          }
        }
      } else {
        ctx.drawImage(img, 0, 0, width, height);
      }

      // 进行最小压缩
      var ndata = canvas.toDataURL("image/jpeg", 0.8);

      console.log("压缩前：" + initSize);
      console.log("压缩后：" + ndata.length);
      console.log(
        "压缩率：" + ~~((100 * (initSize - ndata.length)) / initSize) + "%"
      );

      tCanvas.width = tCanvas.height = canvas.width = canvas.height = 0;
      return ndata;
    }
    // 图片结束
  },
  mounted() {
    let that = this;
    var userinfo = JSON.parse(sessionStorage.getItem("userinfo"));
    if (userinfo && userinfo.vipcode) {
      let userid = userinfo.vipcode;
      this.userid = userid;
    } else {
      //				MessageBox({
      //		            title: "提示",
      //		            message: "您还不是会员",
      //		            showCancelButton: true,
      //		            showCancelButton: false,
      //		            confirmButtonText: "去注册",
      //		            closeOnClickModal: false,
      //		            confirmButtonClass: "zcbtn"
      //		        }).then(action => {
      //		            // 跳转到积分列表
      //		            that.$router.push({path: "/register",query: {type: 'qdpage'}});
      //		        });
      Toast({
        message: "您还不是会员，快去注册吧！",
        duration: 1600
      });
      setTimeout(function() {
        that.$router.push({ path: "/register", query: { type: "sign" } });
      }, 1600);
      return false;
    }
  }
};
</script>

<style lang="less">
.sendtalk {
  .st_box {
    padding: 0.26rem;
    .title {
      border-bottom: 0.01rem solid #dddddd;
      input {
        border: none;
        height: 0.9rem;
        padding: 0 0.1rem;
        width: 100%;
        font-size: 0.32rem;
      }
    }
    .whead {
      border-left: 0.06rem solid #F05DC4;
      padding-left: 0.14rem;
      height: 0.36rem;
      line-height: 0.36rem;
      margin: 0.24rem 0;
      font-size: 0.32rem;
    }
    .kanfa {
      .inbox {
        border: 0.01rem solid #dddddd;
        border-radius: 0.1rem;
      }
    }
  }
  .upph {
    .chooseImg {
      padding-bottom: 0.2rem;
      /*border-bottom: 0.01rem solid #EEEEEE;*/
    }
    .chooseImg .head {
      display: flex;
      justify-content: space-between;
      padding: 0.2rem 0;
    }
    .chooseImg .head span {
      font-size: 0.32rem;
    }
    .chooseImg .head div {
      font-size: 0.3rem;
      color: #ccc;
    }
    .page-body-info {
      display: flex;
      flex-direction: row;
      flex-wrap: wrap;
    }
    /*.hasPh {
				width: 2rem;
				height: 2rem;
				position: relative;
				margin: 0.1rem;
				border-radius: 0.1rem;
				img {
					width: 2rem;
					height: 2rem;
					border-radius: 0.1rem;
				}
			}*/
    .hasPh {
      width: 2rem;
      height: 2rem;
      margin: 0.1rem;
      position: relative;
      .phbox {
        display: flex;
        justify-content: center;
        align-items: center;
        width: 100%;
        height: 2rem;
        overflow: hidden;
        border-radius: 0.1rem;
        img {
          width: 100%;
          /*height: 1.6rem;*/
          height: auto;
          border-radius: 0.1rem;
        }
      }
    }
    .hasPh .clear {
      position: absolute;
      right: -0.1rem;
      top: -0.1rem;
      width: 0.3rem;
      height: 0.3rem;
      border-radius: 50%;
      background-color: #ccc;
      color: #fff;
      font-size: 0.3rem;
      text-align: center;
      line-height: 0.3rem;
    }
    .chooseImg .chooseBtn {
      width: 2rem;
      height: 2rem;
      border: 0.02rem solid #ddd;
      position: relative;
      margin: 0.1rem;
      overflow: hidden;
      border-radius: 0.1rem;
      input {
        width: 100%;
        height: 100%;
        opacity: 0;
        position: absolute;
        left: 0;
        top: 0;
        z-index: 99;
      }
      .add {
        width: 0.8rem;
        height: 0.6rem;
        line-height: 0.6rem;
        position: absolute;
        left: 0.66rem;
        bottom: 0.2rem;
        font-size: 0.36rem;
        color: #cccccc;
      }
    }
    .line-horizontal {
      width: 0.9rem;
      height: 0.06rem;
      background: #d7d7d7;
      position: absolute;
      left: 50%;
      margin-left: -0.45rem;
      top: 0.69rem;
    }
    .line-vertical {
      height: 0.9rem;
      width: 0.06rem;
      background: #d7d7d7;
      position: absolute;
      top: 0.25rem;
      left: 50%;
      margin-left: -0.03rem;
    }
  }
  .tis {
    line-height: 0.7rem;
    color: #999999;
    font-size: 0.26rem;
    display: flex;
    align-items: center;
    i {
      font-size: 0.4rem;
      margin-right: 0.1rem;
    }
  }
  .sendBtn {
    width: 6.98rem;
    height: 0.88rem;
    border-radius: 0.12rem;
    background-color: #F05DC4;
    color: #ffffff;
    font-size: 0.34rem;
    text-align: center;
    line-height: 0.88rem;
    margin: 0 auto;
    margin-top: 0.2rem;
    /*position: fixed;*/
    /*bottom: 0.3rem;*/
    /*left: 50%;*/
    /*margin-left: -2.5rem;*/
    span {
      margin: 0 0.2rem;
    }
  }
  .test {
    position: fixed;
    left: 0.2rem;
    top: 3.5rem;
    background-color: #cccccc;
  }
}
</style>
